/**
 * Created by Mark on 2018/4/11.
 * 用户更新个人信息
 */

require("./user-center-update.css");
require("page/common/nav/nav.js");
require("page/common/header/header.js");
var navSide = require("page/common/nav-side/nav-side.js");
var _user = require("service/user-service.js");
var _mm = require("util/mm.js");
var templateIndex = require("./user-center-update.string");


var page = {
    init : function(){
        this.onLoad();
        this.bindEvent();
    },
    //初始化加载的信息
    onLoad : function(){
        navSide.init({//加载侧边导航
            name : "user-info-update",
        });
        this.loadUserInfo();//加载用户信息
    },
    bindEvent : function(){
        var _this = this;
        $(document).on("click","#submit",function(){
           var userInfo = {
               phone : $.trim($("#phone").val()),
               email : $.trim($("#email").val()),
               question : $.trim($("#question").val()),
               answer : $.trim($("#answer").val())
           };
            var validateResult = _this.validateFrom(userInfo);
            if(validateResult.status){//验证通过
                _user.updateUserInfo(userInfo,
                function(res){
                    _mm.successTips(res.msg);
                    window.location.href = "./user-center.html";
                },
                function(err){
                    _mm.errorTips(err.msg);
                });
            }else{
                _mm.errorTips(validateResult.msg);
            }
        });

    },
    validateFrom : function(formData){
        var result = {
            status : false,
            msg : ""
        };
        //验证手机号的格式
        if(!_mm.validate(formData.phone,"phone")){
            result.msg = "输入的手机号格式不正确！";
            return result;
        }
        //验证email格式
        if(!_mm.validate(formData.email,"email")){
            result.msg = "输入的邮箱格式不正确";
            return result;
        }
        //验证找回密码的提示问题不为空
        if(!_mm.validate(formData.question,"require")){
            result.msg = "问题不能为空！";
            return result;
        }
        //验证问题的答案不能为空
        if(!_mm.validate(formData.answer,"require")){
            result.msg = "回答问题的答案不能为空！"
            return result;
        }
        //通过验证返回，正确提示
        result.status = true;
        result.msg = "验证通过";
        return result;
    },
    loadUserInfo : function(){
        var userHtml = "";
        _user.getUserInfo(
            function(res){//请求成功时的回调函数
                userHtml = _mm.renderHtml(templateIndex,res.data);
                $(".panel-body").html(userHtml);
            },
            function(err){//请求失败时的回调函数
                _mm.errorTips(err);
            }
        );
    }

};
$(function(){
    page.init();
});

